package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.android.ui.dialog.ReadOverDialog;
import com.shwread.android.ui.widget.BookmarkPopup;
import com.shwread.android.ui.widget.PopWindowBg;
import com.shwread.android.ui.widget.PopWindowBright;
import com.shwread.android.ui.widget.PopWindowFontSize;
import com.shwread.android.ui.widget.PopWindowJump;
import com.shwread.android.ui.widget.PopWindowSelection;
import com.shwread.android.ui.widget.PopWindowSet;
import com.shwread.android.ui.widget.ReaderMenuItem;
import com.shwread.android.ui.widget.ReadingPopWindow;
import com.shwread.android.ui.widget.SelectCursorPopup;
import com.shwread.android.ui.widget.ShowBookNotePOPUP;
import com.shwread.android.ui.widget.TextSearchPopup;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.http.util.JSONUtil;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.util.NetUtil;
import com.tgx.tina.android.task.ATaskService;

import org.apache.http.Header;
import org.geometerplus.android.fbreader.BookmarkClearAction;
import org.geometerplus.android.fbreader.BookmarkClopboardAction;
import org.geometerplus.android.fbreader.BookmarkRemarkAction;
import org.geometerplus.android.fbreader.ChangeDirectoryAction;
import org.geometerplus.android.fbreader.ClosePopWindowSettingAction;
import org.geometerplus.android.fbreader.GotoBookmarkAction;
import org.geometerplus.android.fbreader.OpenOnlineBookAction;
import org.geometerplus.android.fbreader.OrientationUtil;
import org.geometerplus.android.fbreader.PopupPanel;
import org.geometerplus.android.fbreader.PopupWindowSettingAction;
import org.geometerplus.android.fbreader.SearchAction;
import org.geometerplus.android.fbreader.SelectionCopyAction;
import org.geometerplus.android.fbreader.SelectionHighLightAction;
import org.geometerplus.android.fbreader.SelectionRemarkAction;
import org.geometerplus.android.fbreader.SelectionShowPanelAction;
import org.geometerplus.android.fbreader.SelectionShowPopupAction;
import org.geometerplus.android.fbreader.SetScreenOrientationAction;
import org.geometerplus.android.fbreader.SetSwitchBackGrounAction;
import org.geometerplus.android.fbreader.ShowBookNotePOPUPAction;
import org.geometerplus.android.fbreader.api.ApiListener;
import org.geometerplus.android.fbreader.api.ApiServerImplementation;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.android.util.QyreaderPerferencesUtil;
import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.Bookmark;
import org.geometerplus.fbreader.book.BookmarkQuery;
import org.geometerplus.fbreader.book.HighlightingStyle;
import org.geometerplus.fbreader.book.SerializerUtil;
import org.geometerplus.fbreader.fbreader.ActionCode;
import org.geometerplus.fbreader.fbreader.ColorProfile;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.fbreader.fbreader.FBView;
import org.geometerplus.fbreader.fbreader.SetLineSpaceAction;
import org.geometerplus.fbreader.fbreader.SwitchProfileAction;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.library.ZLibrary;
import org.geometerplus.zlibrary.core.util.ZLColor;
import org.geometerplus.zlibrary.core.view.ZLView.PageIndex;
import org.geometerplus.zlibrary.text.view.ZLTextView;
import org.geometerplus.zlibrary.ui.android.application.ZLAndroidApplicationWindow;
import org.geometerplus.zlibrary.ui.android.library.ZLAndroidApplication;
import org.geometerplus.zlibrary.ui.android.library.ZLAndroidLibrary;
import org.geometerplus.zlibrary.ui.android.view.AndroidFontUtil;
import org.geometerplus.zlibrary.ui.android.view.LQReadingView;
import org.geometerplus.zlibrary.ui.android.view.ZLAndroidPaintContext;
import org.json.JSONException;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import logic.bean.BookBean;
import logic.bean.TOCItem;
import logic.beanenum.BookStatus_Enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.BookDao;
import logic.util.FileUtil;
import logic.util.ScreenUtil;
import logic.util.Util;
import logic.util.qryChapterInfoUtil;
import logic.xml.parser.NCXHandler;


/**
 * @Title ReadingBookActivity.java
 * @Description 看书界面
 * @author fw
 * @Crtdate 2014-1-14下午3:46:15
 */
public class ReadingBookActivity
        extends
        BaseSimpleActivity
{
	public static String               DEFAULT_CHAPTERID = "518"; //主要用于本地书籍的默认章节id
	public static final int            ANNOTATION_REQUEST_CODE = 118 ; 
	public static int                  BatteryLevel;                                        //电量
	public static final int            ACTION_BAR_COLOR    = Color.DKGRAY;
	public static final String         SHOW_CATALOG        = "showCatelog";
	public static final String         TAG                 = "ReadingBook";
	public static final String         ACTION_OPEN_BOOK    = "android.fbreader.action.VIEW";
	public static final String         BOOK_KEY            = "fbreader.book";
	public static final String         BOOKMARK_KEY        = "fbreader.bookmark";
	private static final int                  GET_CHAPTERINFO_OK    = 118;
	private static final int                  GET_CHAPTERINFO_ERROR = 119;	
	
	private Context                    mContext;
	
	public FBReaderApp                 myFBReaderApp;
	private volatile Book              myBook;
	
	/** VIEW */
	private LQReadingView              myMainView;
	private FrameLayout                reading_pop_fl;
	private View                       topUtilView;
	private View                       bottomUtilView;
	private RelativeLayout             myRootView;
	private ImageView                  mIVBookMark;
	/** ACTION */
	//	private UpdateBookLastOpenTimeAction<BaseBusinessActivity> updateBookLastOpenTimeAction;
	//	private AddBookAnnotionAction<BaseBusinessActivity>        addBookAnnotionAction;
	//	UpdateBookContentIdAction<BaseBusinessActivity>            updateBookContentIdAction;
	
	public static String               contentId;
	public static String               chapterId;
	public static String               bookname;
	
	private int                        myFullScreenFlag;
	
	private final BookCollectionShadow myCollection        = new BookCollectionShadow();
	
	final static byte                  select_popup_Adjust = 60;
	final static byte                  select_popup_New    = 61;
	private LayoutInflater             inflater;
	
	private CleanSelectCursor          selectcursor;
	public static final String         BOOKSTATUS          = "bookstatus";                  //在线，离线，本地导入
	private int                        bookstatus          = 2;                             //1本地书籍  2在线书籍 3 下载 4 推荐
	private List<TOCItem>              catalogList;
	private int                        chapterIndex = -1;
	
	private QyreaderPerferencesUtil xmlUtil;
	
	public Handler getUIHandler() {
		return myHandler;
	}
	
	private Handler myHandler = new Handler()
	                          {
		                          public void handleMessage(Message msg) {
			                          switch (msg.what) {
										  case DefaultConsts.UPDATEUI_READING_BOOK:
											  myFBReaderApp.getViewWidget().repaint();
											  break;
										  case 1:
											  mIVBookMark.setVisibility(View.GONE);
											  break;
										  case GET_CHAPTERINFO_OK:
											  chapterId = myBook.getChapterId();
											  //open chapter
											  myFBReaderApp.openChapter(chapterId,  myOpenStyle);
											  break;
										  case GET_CHAPTERINFO_ERROR:
											  myFBReaderApp.setDontCloseLoading(false);
											  closeLoading();
											  Bundle bundle = msg.getData();
											  Util.showToast(mContext, bundle.getString("message"));
											  ReadingBookActivity.this.finish();
											  break;
									  }
								  };
	                          };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.reading__reading_view);
		inflater = LayoutInflater.from(ReadingBookActivity.this);
		registerReceiver(myBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
		
		myRootView = (RelativeLayout) findViewById(R.id.reading_reading_view_root);
		myMainView = (LQReadingView) findViewById(R.id.main_view);
		mIVBookMark = (ImageView) findViewById(R.id.reading__reading_view__bookmark);
		
		catalogList = new ArrayList<TOCItem>();
		
		mContext = this;
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		initConst();
		
		getZLibrary().setActivity(this);
		
		myFBReaderApp = (FBReaderApp) FBReaderApp.Instance();
		if (myFBReaderApp == null)
		{
			myFBReaderApp = new FBReaderApp(myCollection);
		}
		myFBReaderApp.setReaderActivity(this);
		
		myFBReaderApp.contentId = contentId;
		myFBReaderApp.chapterId = "-1";
		myFBReaderApp.chapterName = "";
		myBook = null;
		
		initPopMenu();
		
		final ZLAndroidApplication androidApplication = (ZLAndroidApplication) getApplication();
		if (androidApplication.myMainWindow == null)
		{
			androidApplication.myMainWindow = new ZLAndroidApplicationWindow(myFBReaderApp);
			myFBReaderApp.initWindow();
		}
		
		final ZLAndroidLibrary zlibrary = (ZLAndroidLibrary) ZLibrary.Instance();
		myFullScreenFlag = zlibrary.ShowStatusBarOption.getValue() ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, myFullScreenFlag);
		
		
		if (myFBReaderApp.getPopupById(BookmarkPopup.ID) == null)
		{
			new BookmarkPopup(myFBReaderApp);
		}
		
		SelectCursorPopup.AddPopup(select_popup_Adjust, inflater.inflate(R.layout.selectcursor, null), new OnClickListener()
		{
			
			@Override
			public void onClick(View v) {
				
				switch (v.getId()) {
					case R.id.select_Copy:
						myFBReaderApp.runAction(ActionCode.SELECTION_COPY_TO_CLIPBOARD, mBookmark);
						SelectCursorPopup.Hide();
						break;
					
					case R.id.select_Note:
						SelectCursorPopup.Hide();
						myFBReaderApp.runAction(ActionCode.BOOKMARK_BOOKREMARK);
						break;
					
					case R.id.select_Delete:
						SelectCursorPopup.Hide();
						myFBReaderApp.runAction(ActionCode.BOOKMARK_CLEAR);
						break;
				}
			}
		}, false);
		
		SelectCursorPopup.AddPopup(select_popup_New, inflater.inflate(R.layout.new_selectcursor, null, true), new OnClickListener()
		{
			
			@Override
			public void onClick(View v) {
				
				switch (v.getId()) {
					case R.id.select_AddCopy:
						myFBReaderApp.runAction(ActionCode.SELECTION_COPY_TO_CLIPBOARD, mBookmark);
						SelectCursorPopup.Hide();
						break;
					
					case R.id.select_AddNote:
						SelectCursorPopup.Hide();
						myFBReaderApp.runAction(ActionCode.SELECTION_BOOKREMARK);
						break;
					
					case R.id.select_AddHighlight:
						SelectCursorPopup.Hide();
						myFBReaderApp.runAction(ActionCode.SELECTION_HIGHLIGHT);
						break;
				}
			}
		}, true);
		
		myFBReaderApp.addAction(ActionCode.SHOW_POPWINDOW_MENU, new PopupWindowSettingAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.HIDE_POPWINDOW_MENU, new ClosePopWindowSettingAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_SYSTEM, new SetScreenOrientationAction(this, myFBReaderApp, ZLibrary.SCREEN_ORIENTATION_SYSTEM));
		myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_SENSOR, new SetScreenOrientationAction(this, myFBReaderApp, ZLibrary.SCREEN_ORIENTATION_SENSOR));
		myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_PORTRAIT, new SetScreenOrientationAction(this, myFBReaderApp, ZLibrary.SCREEN_ORIENTATION_PORTRAIT));
		myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_LANDSCAPE, new SetScreenOrientationAction(this, myFBReaderApp, ZLibrary.SCREEN_ORIENTATION_LANDSCAPE));
		myFBReaderApp.addAction(ActionCode.SELECTION_COPY_TO_CLIPBOARD, new SelectionCopyAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.SELECTION_HIGHLIGHT, new SelectionHighLightAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.SELECTION_BOOKREMARK, new SelectionRemarkAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.SELECTION_SHOW_PANEL, new SelectionShowPanelAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.SET_LINE_SPACE, new SetLineSpaceAction(myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.BOOKMARK_CLEAR, new BookmarkClearAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.BOOKMARK_CLIPBOARD, new BookmarkClopboardAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.BOOKMARK_BOOKREMARK, new BookmarkRemarkAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.SHOW_BOOK_NOTE_POPUP, new ShowBookNotePOPUPAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.OPEN_ONLINE_BOOKS, new OpenOnlineBookAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.CHANGE_DIRECTORY_BOOKS, new ChangeDirectoryAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.GOTO_BOOKMARK, new GotoBookmarkAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.SELECTION_SHOW_POPUP, new SelectionShowPopupAction(this, myFBReaderApp));
		myFBReaderApp.addAction(ActionCode.SWITCH_TO_CHANGE_BRIGHT, new SetSwitchBackGrounAction(this, myFBReaderApp));
		if (ZLibrary.Instance().supportsAllOrientations())
		{
			myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_REVERSE_PORTRAIT, new SetScreenOrientationAction(this, myFBReaderApp, ZLibrary.SCREEN_ORIENTATION_REVERSE_PORTRAIT));
			myFBReaderApp.addAction(ActionCode.SET_SCREEN_ORIENTATION_REVERSE_LANDSCAPE, new SetScreenOrientationAction(this, myFBReaderApp, ZLibrary.SCREEN_ORIENTATION_REVERSE_LANDSCAPE));
		}
		myFBReaderApp.addAction(ActionCode.SEARCH, new SearchAction(this, myFBReaderApp));
		
		if (myFBReaderApp.getPopupById(TextSearchPopup.ID) == null)
		{
			new TextSearchPopup(myFBReaderApp);
		}
		
		setWindowBright( );
		
		mAService = new ATaskService();
		mAService.startAService(this);
		
		
		ShowFirestIn();
		
	}

	
	/**
	 * 第一次进看书界面引导页
	 */
	private void ShowFirestIn() {
		xmlUtil=  QyreaderPerferencesUtil.getInstance(mContext, Const.phone_number);
//		xmlUtil.setFirstReading(true);//测试
		if (xmlUtil.isFirstReading())
		{
			final Dialog readingFirstInDialog = new Dialog(ReadingBookActivity.this,
					R.style.ReadingBookFirstInGuidDialog);
			View readingFirstInDialogView = getLayoutInflater().inflate(R.layout.reading_book_firstin, null);
			readingFirstInDialog.setContentView(readingFirstInDialogView);
			Button closeBtn = (Button) readingFirstInDialogView.findViewById(R.id.reading_book_firstin_btn);
			closeBtn.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					readingFirstInDialog.dismiss();
					xmlUtil.setFirstReading(false);
				}
			});
			readingFirstInDialog.show();
		}
	}
	
	public ZLAndroidPaintContext getInitPaintContext( ) {
		return myMainView.getInitPaintContext();
	}
	
	public boolean isMenuShowing() {
		return (topUtilView.getVisibility() == View.GONE) ? true : false;
	}
	
	@Override
	public void openOptionsMenu() {
		if (null != popWindowSelection)
		{
			if (popWindowSelection.isShow())
			{
				return;
			}
			else
			{
				_showMenu();
				myFBReaderApp.setMenuShowing(true);
			}
		}
		else
		{
			_showMenu();
			myFBReaderApp.setMenuShowing(true);
		}
	}
	
	@Override
	public void closeOptionsMenu() {
		_hideMenu();
		myFBReaderApp.setMenuShowing(false);
	}
	
	public void openChapterByAsync(final Object... params) {
		showLoading();
		myHandler.post(new Runnable()
		{
			@Override
			public void run() {
				openChapter(params); 
			}
		});
	}
	
	private void openChapter(Object... params) {
		
		
		PageIndex pageindex = (PageIndex) params[0];
		// #debug
		base.tina.core.log.LogPrinter.d("openOnlineBook", "pageindex" + pageindex);
		chapterIndex = myFBReaderApp.getCurrentChapterIndex();
		
		
		
		if (myBook != null)
		{
			if (bookstatus == 1)//本地
			{
				//最后一页
				if( pageindex == PageIndex.next ) {
				    showReadOverDialog();
				}
				closeLoading();
			}
			else if (bookstatus == 3)//离线
			{
				if (pageindex == PageIndex.next)
				{
					if (chapterIndex + 1 == catalogList.size())
					{
						//最后一章
						showReadOverDialog();
						closeLoading();
						return;
					}
					else
					{   //下一章
						QyreaderPerferencesUtil.getInstance(this, Const.phone_number).setChapterIndex(contentId, chapterIndex+1);
						chapterId = catalogList.get(chapterIndex + 1).getId();
						myFBReaderApp.openChapter(chapterId, 1);
					}
				}
				else
				{
					//上 一章
					if (chapterIndex <= 0) {
						closeLoading();
						return;
					}
					QyreaderPerferencesUtil.getInstance(this, Const.phone_number).setChapterIndex(contentId, chapterIndex-1);
					chapterId = catalogList.get(chapterIndex - 1).getId();
					myFBReaderApp.openChapter(chapterId, 2);
				}
			}
			else
			{
				//无网络时
				if (NetUtil.isNetworkConnected(mContext))
				{
					if (pageindex == PageIndex.next)
					{
						if (chapterIndex == (catalogList.size() - 1))
						{
							showReadOverDialog();
							closeLoading();
							return;
						}
						QyreaderPerferencesUtil.getInstance(this, Const.phone_number).setChapterIndex(contentId, chapterIndex+1);
						chapterId = catalogList.get(chapterIndex + 1).getId();
						//打开下一章节
						openChapterReally(chapterId, 1);
						
						// 预下载
						if (chapterIndex < (catalogList.size() - 2))//点击最后一章
						{
							String next = catalogList.get(chapterIndex + 2).getId();
							if (!FileUtil.FileExist(contentId, next + ".html"))
							{
//								new QryChapterInfoAction(this, contentId, next, null).start();
								new qryChapterInfoUtil().qryChapterInfo(this, contentId, next);
							}
						}
					}
					else if (pageindex == PageIndex.previous)
					{
						if(0==chapterIndex)
						{
							Util.showToast(mContext, "已经是第一页");
						}
						if (chapterIndex - 1 < 0) {
							closeLoading();
							return;
						}
						QyreaderPerferencesUtil.getInstance(this, Const.phone_number).setChapterIndex(contentId, chapterIndex-1);
						chapterId = catalogList.get(chapterIndex - 1).getId();
						//打开上一章节
						openChapterReally(chapterId, 2);
						if (chapterIndex > 1)//点击第一章
						{
							String preview = catalogList.get(chapterIndex - 2).getId();
							if (!FileUtil.FileExist(contentId, preview + ".html"))
							{
//								new QryChapterInfoAction(this, contentId, preview, null).start();
								new qryChapterInfoUtil().qryChapterInfo(this, contentId, preview);
							}
						}
					}
				}
				else
				{
					//翻页无网络时的操作
					new NetworkDialog(mContext).show();
				}
			}
		}
	}
	int myOpenStyle = 0;
	private void openChapterReally( String chapterId,  int openStyle) {
		if (bookstatus == BookStatus_Enum.DOWNLOAD.getValue() || bookstatus == BookStatus_Enum.LOCAL.getValue() || FileUtil.FileExist(contentId, chapterId + ".html"))
		{
			myFBReaderApp.openChapter(chapterId, openStyle);
		}
		else
		{
			myBook.setChapterId(chapterId);
			myOpenStyle = openStyle;
		    downloadChapterInfo(chapterId);
		}
	}
	
	public List<TOCItem> getCatalogList( ) {
		return catalogList;
	}
	
	public void setCatalogList(List<TOCItem> catalogs ) {
		catalogList = catalogs ;
	}
	
	public void changeDirectory(Object... params) {
		chapterId = (String) params[1];
		showLoading();
		myHandler.post(new Runnable()
		{
			@Override
			public void run() {
				openChapterReally(chapterId,  1);
			}
		});
	}
	
	public void gotoBookMark(Object... params) {
		chapterId = (String) params[0];
		int paraIndex = (Integer)params[1];
		int wordIndex = (Integer)params[2];
		int charIndex = (Integer)params[3];
		myFBReaderApp.setGotoPosition(paraIndex, wordIndex, charIndex);
		showLoading();
		myHandler.post(new Runnable()
		{
			@Override
			public void run() {
				openChapterReally(chapterId,  4);
			}
		});
	}
	
	public void reopenCurrentChapter( ){
		//showLoading();
		myHandler.post(new Runnable()
		{
			@Override
			public void run() {
				chapterId = myBook.getChapterId();
				myFBReaderApp.openChapter(chapterId, 3);
			}
		});
	}
	
	private void setWindowBright( ) {
		int bright = myFBReaderApp.brightOption.getValue();
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.screenBrightness = (55 + bright * 2) / 255.0f;
		getWindow().setAttributes(lp);
	}
	
	private void _showMenu() {
		reading_pop_fl.setVisibility(View.VISIBLE);
		topUtilView.setVisibility(View.VISIBLE);
		bottomUtilView.setVisibility(View.VISIBLE);
		Animation animationTop = AnimationUtils.loadAnimation(this, R.anim.common_top_in);
		topUtilView.setAnimation(animationTop);
		animationTop.start();
		Animation animationBottom = AnimationUtils.loadAnimation(this, R.anim.common_bottom_in);
		bottomUtilView.setAnimation(animationBottom);
		animationBottom.start();
	}
	
	public void _hideMenu() {
		Animation animationTop = AnimationUtils.loadAnimation(this, R.anim.common_top_out);
		topUtilView.setAnimation(animationTop);
		animationTop.start();
		Animation animationBottom = AnimationUtils.loadAnimation(this, R.anim.common_bottom_out);
		bottomUtilView.setAnimation(animationBottom);
		animationBottom.start();
		topUtilView.setVisibility(View.GONE);
		bottomUtilView.setVisibility(View.GONE);
		reading_pop_fl.setVisibility(View.GONE);
	}
	
	/**
	 * 选择文字后的popup
	 */
	public void showSelectionPanel() {
		final ZLTextView view = myFBReaderApp.getTextView();
		SelectCursorPopup.Show(select_popup_New, 0.8f, ScreenUtil.dip2px(40f), myRootView, false, true, view.getSelectionStartY(), view.getSelectionEndY());
	}
	
	/**
	 * 再次点击笔记时popup
	 */
	public void showBookmarkPanel(Bookmark bookmark) {
		mBookmark = bookmark;
		final ZLTextView view = myFBReaderApp.getTextView();
		((BookmarkPopup) myFBReaderApp.getPopupById(BookmarkPopup.ID)).move(view.getSelectionStartY(), view.getSelectionEndY());
		myFBReaderApp.showPopup(BookmarkPopup.ID);
		
	}
	
	Bookmark mBookmark;
	
	public void clearSelectionBookmark() {
		myFBReaderApp.deleteRemarkIcon(mBookmark);
		getCollection().deleteBookmark(mBookmark);
		myFBReaderApp.getViewWidget().reset();
		myFBReaderApp.getViewWidget().repaint();
	}
	
	@SuppressLint("NewApi")
	public void copyBookmarkClipboard() {
		String text = mBookmark.getText();
		if (android.os.Build.VERSION.SDK_INT > 11)
		{
			android.content.ClipboardManager c = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
			c.setText(text);
			Util.showToast(this, c.getText() + "");
		}
		else
		{
			android.text.ClipboardManager c = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
			c.setText(text);
			Util.showToast(this, c.getText() + "");
		}
	}
	
	public void showBookNotePOPUP(Object... params) {
		Bookmark bookmark = (Bookmark) params[0];
		Point point = (Point) params[1];
		mBookmark = bookmark;
		ShowBookNotePOPUP showBookNotePOPUP = ShowBookNotePOPUP.getInstance(this, bookmark);
		// showBookNotePOPUP.show(myRootView, point.x, point.y);
		showBookNotePOPUP.show2(myRootView, point.x, point.y);
	}
	
	PopWindowSelection popWindowSelection;
	
	public void showPopWindow(Object... params) {
		
		final ZLTextView view = myFBReaderApp.getTextView();
		SelectCursorPopup.Show(select_popup_New, 0.8f, ScreenUtil.dip2px(40f), myRootView, false, true, view.getSelectionStartY(), view.getSelectionEndY());
	}
	
	public void showPopWindowValid(int x, int y, Bookmark bookmark) {
		mBookmark = bookmark;
		SelectCursorPopup.Show(select_popup_Adjust, 0.8f, y, ScreenUtil.dip2px(40f), myRootView, false, true);
	}
	
	public void changeBooKRemark(Bookmark bookmark) {
		final Intent intent = new Intent(this, NotesActivity.class);
		NotesActivity.myBookmark = mBookmark;
		intent.putExtra(NotesActivity.EXISTING_BOOKMARK_KEY, true);
		OrientationUtil.startActivity(this, intent);
	}
	
	public void changeBooKRemark() {
		final Intent intent = new Intent(this, NotesActivity.class);
		NotesActivity.myBookmark = mBookmark;
		intent.putExtra(NotesActivity.EXISTING_BOOKMARK_KEY, true);
		OrientationUtil.startActivity(this, intent);
	}
	
	public void setSwitchBackground() {
		menuItems[2].changeTextRes(R.string.menu_night);
		menuItems[2].changeImageRes(R.drawable.menu_icon_night_bg);
	}
	
	private void initPopMenu() {
		reading_pop_fl = (FrameLayout) findViewById(R.id.reading_pop_fl);
		topUtilView = findViewById(R.id.reading_pop_top);
		bottomUtilView = findViewById(R.id.reading_pop_bottom);
		reading_pop_fl.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v) {
				_hideMenu();
			}
		});
		initTopMenu();
		initBottomMenu();
	}
	
	private void initTopMenu() {
		OnClickListener clickListener = new OnClickListener()
		{
			
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
					case R.id.reader_pop_top_btn_return:
						onBackPressed0();
						break;
					case R.id.reader_pop_top_btn_search:
						_hideMenu();
						myFBReaderApp.runAction(ActionCode.SEARCH);
						break;
					case R.id.reader_pop_top_btn_bookmark:
						Bookmark bookmark = myFBReaderApp.createBookmark(100, true, contentId);
						boolean has = false;
						for (BookmarkQuery query = new BookmarkQuery(myBook, 100);; query = query.next())
						{
							List<Bookmark> bookmarks = getCollection().bookmarks(query);
							if (bookmarks.isEmpty()) break;
							
							for (Bookmark bookmark2 : bookmarks)
							{
								if (bookmark2.getText().equals(bookmark.getText()))
								{
									has = true;
									break;
								}
							}
							if (has) break;
						}
						
						if (!has)
						{
							getCollection().saveBookmark(bookmark);
						}
						
						_hideMenu();
						mIVBookMark.setVisibility(View.VISIBLE);
						Animation animation = AnimationUtils.loadAnimation(ReadingBookActivity.this, R.anim.bookmark_show);
						mIVBookMark.setAnimation(animation);
						animation.start();
						myHandler.sendEmptyMessageDelayed(1, 2000);
						Util.showToast(ReadingBookActivity.this, "书签已保存");
						break;
				}
			}
		};
		
		Button btnBack = (Button) findViewById(R.id.reader_pop_top_btn_return);
		ImageButton btnSearch = (ImageButton) findViewById(R.id.reader_pop_top_btn_search);
		ImageButton btnAddBookMark = (ImageButton) findViewById(R.id.reader_pop_top_btn_bookmark);
		btnBack.setOnClickListener(clickListener);
		btnSearch.setOnClickListener(clickListener);
		btnAddBookMark.setOnClickListener(clickListener);
		btnAddBookMark.setVisibility(View.VISIBLE);
		btnSearch.setVisibility(View.VISIBLE);
	}
	
	/**
	 * 获得锁屏时间 毫秒
	 */
	private int getScreenOffTime() {
		int screenOffTime = 0;
		try
		{
			screenOffTime = android.provider.Settings.System.getInt(this.getContentResolver(), android.provider.Settings.System.SCREEN_OFF_TIMEOUT);
		}
		catch (Exception localException)
		{
			
		}
		return screenOffTime;
	}
	
	ReaderMenuItem[] menuItems;
	
	private void initBottomMenu() {
		menuItems = new ReaderMenuItem[8];
		menuItems[0] = (ReaderMenuItem) findViewById(R.id.menu_catelog_ll);
		menuItems[1] = (ReaderMenuItem) findViewById(R.id.menu_landscape_ll);
		menuItems[1].setTag(ActionCode.SET_SCREEN_ORIENTATION_PORTRAIT);
		menuItems[2] = (ReaderMenuItem) findViewById(R.id.menu_daynight_ll);
		menuItems[3] = (ReaderMenuItem) findViewById(R.id.menu_bright_ll);
		menuItems[4] = (ReaderMenuItem) findViewById(R.id.menu_jump_ll);
		menuItems[5] = (ReaderMenuItem) findViewById(R.id.menu_bg_ll);
		menuItems[6] = (ReaderMenuItem) findViewById(R.id.menu_font_ll);
		menuItems[7] = (ReaderMenuItem) findViewById(R.id.menu_setting_ll);
		String[] texArray = getResources().getStringArray(R.array.menu_bottom_tx_array);
		int[] ivArray = new int[] {
		        R.drawable.menu_icon_catalog_bg,
		        R.drawable.menu_icon_landscape_bg,
		        R.drawable.menu_icon_night_press,
		        R.drawable.menu_icon_brightness_bg,
		        R.drawable.menu_icon_jump_bg,
		        R.drawable.menu_icon_bg_bg,
		        R.drawable.menu_icon_font_bg,
		        R.drawable.menu_icon_setting_bg
		};
		OnClickListener clickListener = new OnClickListener()
		{
			
			@Override
			public void onClick(View v) {
				_hideMenu();
				topUtilView.setVisibility(View.GONE);
				bottomUtilView.setVisibility(View.GONE);
				if (v == menuItems[0])
				{
					if( catalogList == null) {
						 //Util.showToast(mContext, "没有目录数据，无法切换！");
					}
					Intent intent = new Intent();
					intent.setClass(mContext, AnnotationsActivity.class);
					intent.putExtra(DefaultConsts.book_contentId_s, contentId);
					intent.putExtra(DefaultConsts.chapterId_index_i, chapterId);
					intent.putExtra(DefaultConsts.chapterId_current_i, myFBReaderApp.getCurrentChapterIndex());
					intent.putExtra(DefaultConsts.book_name, bookname);
					intent.putExtra(BOOKSTATUS, bookstatus);
					//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
					AnnotationsActivity.myBook = myBook;
					startActivityForResult(intent, ANNOTATION_REQUEST_CODE);
				}
				else if (v == menuItems[1])
				{
					myFBReaderApp.storePosition();
					if (v.getTag().equals(ActionCode.SET_SCREEN_ORIENTATION_LANDSCAPE))
					{
						myFBReaderApp.runAction(ActionCode.SET_SCREEN_ORIENTATION_PORTRAIT);
						v.setTag(ActionCode.SET_SCREEN_ORIENTATION_PORTRAIT);
						menuItems[1].changeTextRes(R.string.menu_landscape_h);
					}
					else
					{
						myFBReaderApp.runAction(ActionCode.SET_SCREEN_ORIENTATION_LANDSCAPE);
						v.setTag(ActionCode.SET_SCREEN_ORIENTATION_LANDSCAPE);
						menuItems[1].changeTextRes(R.string.menu_landscape_v);
					}
				}
				else if (v == menuItems[2])
				{
					if (myFBReaderApp.getColorProfileName().equals(ColorProfile.NIGHT))
					{
						myFBReaderApp.runAction(ActionCode.SWITCH_TO_DAY_PROFILE, new SwitchProfileAction(myFBReaderApp, ColorProfile.DAY));
						//						v.setTag(ActionCode.SWITCH_TO_DAY_PROFILE);
						menuItems[2].changeTextRes(R.string.menu_night);
						menuItems[2].changeImageRes(R.drawable.menu_icon_night_bg);
					}
					else
					{
						myFBReaderApp.runAction(ActionCode.SWITCH_TO_NIGHT_PROFILE, new SwitchProfileAction(myFBReaderApp, ColorProfile.NIGHT));
						//						v.setTag(ActionCode.SWITCH_TO_NIGHT_PROFILE);
						menuItems[2].changeTextRes(R.string.menu_daynight);
						menuItems[2].changeImageRes(R.drawable.menu_icon_daynight_bg);
					}
				}
				else if (v == menuItems[3])
				{
					ReadingPopWindow popWindowBright = PopWindowBright.getInstance(ReadingBookActivity.this);
					popWindowBright.showBottom(myRootView);
				}
				else if (v == menuItems[4])
				{
					ReadingPopWindow popWindowJump = new PopWindowJump(ReadingBookActivity.this);
					popWindowJump.showBottom(myRootView);
				}
				else if (v == menuItems[5])
				{
					ReadingPopWindow popWindowBg = PopWindowBg.getInstance(ReadingBookActivity.this);
					popWindowBg.showBottom(myRootView);
				}
				else if (v == menuItems[6])
				{
					myFBReaderApp.storePosition();
					ReadingPopWindow popWindowFontSize = PopWindowFontSize.getInstance(ReadingBookActivity.this);
					popWindowFontSize.showBottom(myRootView);
				}
				else if (v == menuItems[7])
				{
					ReadingPopWindow popWindowSet = new PopWindowSet(ReadingBookActivity.this, getScreenOffTime());
					popWindowSet.showBottom(myRootView);
				}
			}
		};
		for (int i = 0; i < menuItems.length; i++)
		{
			menuItems[i].init(texArray[i], ivArray[i]);
			menuItems[i].setOnClickListener(clickListener);
		}
		
		if (myFBReaderApp.getColorProfileName().equals(ColorProfile.DAY))
		{
			menuItems[2].changeTextRes(R.string.menu_night);
			menuItems[2].changeImageRes(R.drawable.menu_icon_night_bg);
		}
		else
		{
			menuItems[2].changeTextRes(R.string.menu_daynight);
			menuItems[2].changeImageRes(R.drawable.menu_icon_daynight_bg);
		}
		
	}
	/** 更新章节信息 */
	private void updateChapter(long chapterId,int status){
		if(myFBReaderApp.chapterId.equals("-1") && Util.isEmpty(myFBReaderApp.chapterName)) return;
		if(status != BookStatus_Enum.LOCAL.getValue()){
			BookBean bean = new BookBean();
			bean.book_id = Long.valueOf(contentId);
			bean.book_name = bookname;
			bean.account = Const.phone_number;
			bean.server_chapterid = chapterId;
			bean.status = status;
			bean.startTime = startTime;
			bean.endTime = endTime;
			final String chapterName = myFBReaderApp.chapterName;
			bean.chapterName = Util.isEmpty(chapterName)?"--":chapterName;
			BookDao.getInstance(mContext).addBooktoShelf(bean);
		}
	}
	private void initConst() {
		//		updateBookLastOpenTimeAction = new UpdateBookLastOpenTimeAction<BaseBusinessActivity>(this);
		//		addBookAnnotionAction = new AddBookAnnotionAction<BaseBusinessActivity>(this);
		//		updateBookContentIdAction = new UpdateBookContentIdAction<BaseBusinessActivity>(this);
		bookname = getIntent().getStringExtra(DefaultConsts.book_name);
		contentId = getIntent().getStringExtra(DefaultConsts.book_contentId_s);
		boolean isFromCatalog = getIntent().getBooleanExtra("IsFromCatalogActivity" , false);
		if( isFromCatalog) {
			chapterIndex = getIntent().getIntExtra(DefaultConsts.chapterId_index_i, 0);
		}
		
		bookstatus = getIntent().getIntExtra(BOOKSTATUS, 2);
		//书本目录
		initTOC(bookstatus);
	}
	
	private void initTOC(int bookstatus) {
		if (bookstatus == BookStatus_Enum.LOCAL.getValue()) return;
		String dirctory = "";
		if (bookstatus == BookStatus_Enum.ONLINE.getValue())
		{
			dirctory = FileUtil.OnlinePath(contentId) + FileUtil.Book_CATALOGUE;
		}
		else {
			//dirctory = FileUtil.DownloadPath() + contentId + "/META-INF/book.ncx";
			return;
		}
		
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser;
		try
		{
			parser = factory.newSAXParser();
			InputStream is = new FileInputStream(new File(dirctory));
			NCXHandler handle = new NCXHandler();
			parser.parse(is, handle);
			is.close();
			catalogList = handle.getNavPointList();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (ParserConfigurationException e)
		{
			e.printStackTrace();
		}
		catch (SAXException e)
		{
			e.printStackTrace();
		}
		
	}
	private long startTime,endTime;
	@Override
	protected void onStart() {
		super.onStart();
		final ZLAndroidLibrary zlibrary = (ZLAndroidLibrary) ZLibrary.Instance();
		
		final int fullScreenFlag = zlibrary.ShowStatusBarOption.getValue() ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
		if (fullScreenFlag != myFullScreenFlag)
		{
			finish();
			startActivity(new Intent(this, getClass()));
		}
		startTime = System.currentTimeMillis();
		//((PopupPanel) myFBReaderApp.getPopupById(SelectionPopup.ID)).setPanelInfo(this, myRootView);
		//		((PopupPanel) myFBReaderApp.getPopupById(BookmarkPopup.ID)).setPanelInfo(this, myRootView);
		selectcursor = new CleanSelectCursor();
		ReadingBookActivity.this.registerReceiver(selectcursor, new IntentFilter("HideSelect"));
		showLoading();
		myFBReaderApp.setDontCloseLoading(true);
		myHandler.post(new Runnable() {
			@Override
			public void run() {
				startOpenBook();// 要读书了
			}
		});
	}
	
	@Override
	protected void onStop() {
		endTime = System.currentTimeMillis();
		if(Util.isNotEmpty(chapterId)){
			//TODO 更新阅读章节信息
			updateChapter(Long.valueOf(chapterId), bookstatus);
		}
		ApiServerImplementation.sendEvent(this, ApiListener.EVENT_READ_MODE_CLOSED);
		PopupPanel.removeAllWindows(myFBReaderApp, this);
		ReadingBookActivity.this.unregisterReceiver(selectcursor);
		super.onStop();
	}
	@Override
	protected void onPause() {
	    super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		getCollection().unbind();
		try
		{
			unregisterReceiver(myBatteryInfoReceiver);
		}
		catch (IllegalArgumentException e)
		{
		}
		super.onDestroy();
		if (mAService != null) mAService.stopAService();
	}
	
	@Override
	public void onLowMemory() {
		myFBReaderApp.onWindowClosing();
		super.onLowMemory();
	}
	
	public LQReadingView getMainView() {
		return myMainView;
	}
	
	private static ZLAndroidLibrary getZLibrary() {
		return (ZLAndroidLibrary) ZLAndroidLibrary.Instance();
	}
	
	private PowerManager.WakeLock myWakeLock;
	private boolean               myWakeLockToCreate;
	private boolean               myStartTimer;
	
	public final void createWakeLock() {
		if (myWakeLockToCreate)
		{
			synchronized (this)
			{
				if (myWakeLockToCreate)
				{
					myWakeLockToCreate = false;
					myWakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "FBReader");
					myWakeLock.acquire();
				}
			}
		}
		if (myStartTimer)
		{
			myFBReaderApp.startTimer();
			myStartTimer = false;
		}
	}
	
	// 打开一本书的第一步
	private synchronized void openBook(Intent intent, Runnable action, boolean force, int openStyle) {
		if (!force && myBook != null) { 
			myFBReaderApp.setDontCloseLoading(false);
			closeLoading();
			return;
		}
		Bundle bundle = new Bundle();
		bundle.putString(DefaultConsts.book_contentId_s, contentId);
		myBook = SerializerUtil.deserializeBook(intent.getStringExtra(BOOK_KEY));
		final Bookmark bookmark = SerializerUtil.deserializeBookmark(intent.getStringExtra(BOOKMARK_KEY));
		if (myBook == null)
		{
			if (bookstatus == BookStatus_Enum.LOCAL.getValue())
			{
				final Uri data = intent.getData();
				if (data != null)
				{
					myBook = createBookForFile(ZLFile.createFileByPath(data.getPath()));
					myFBReaderApp.chapterName = bookname.substring(0, bookname.lastIndexOf("."));
				}
			}
			else if (bookstatus == BookStatus_Enum.DOWNLOAD.getValue())
			{
				final Uri data = intent.getData();
				String path = data.getPath();
				if (data != null)
				{
					myBook = createBookForFile(ZLFile.createFileByPath(path));
				}
			}
			else
			{
				//在线阅读
				final Uri data = intent.getData();
				String path = data.getPath();
				if (data != null)
				{
					myBook = createBookForFile(ZLFile.createFileByPath(path));
				}
			}
		}
		
		if (myBook != null)
		{
			myBook.setBookStatus(bookstatus);
			myBook.setContentId(contentId);
			startUpdateContentAction();
			myFBReaderApp.openBook(myBook, openStyle);
		} else {
			myFBReaderApp.setDontCloseLoading(false);
			closeLoading();
		}
	}
	
	public synchronized void openInitChapter(int openStyle) {
		String myChapterId = "";
		if( chapterIndex != -1){//从目录中进来的
			catalogList = myBook.getCatalogList();
			if( catalogList != null && catalogList.size() > 0 ) {
				myChapterId = catalogList.get(chapterIndex).getId();
			} 
		} else {//正常进入的
			myChapterId = myBook.getChapterId();
		}
		
		if( Util.isStringEmpty(myChapterId) || myChapterId.equalsIgnoreCase("0"))
		{
			List<TOCItem> catalog = myBook.getCatalogList();
			if( catalog != null && catalog.size() > 0 ) {
				myChapterId = catalog.get(0).getId();
			} else {
				myChapterId = DEFAULT_CHAPTERID;
			}
		}
		chapterId = myChapterId;
		openChapterReally(myChapterId,  openStyle);
		myHandler.post(new Runnable() {
			@Override
			public void run() {
				myFBReaderApp.getViewWidget().repaint();
			}
		});
	}
	
	void startUpdateContentAction() {
		//TODO 更新书籍阅读时间
		BookDao.getInstance(mContext).updateReadTime(new BookBean(Long.valueOf(contentId), bookname, Const.phone_number, String.valueOf(System.currentTimeMillis())));
		//		new UpdateBookLastOpenTimeAction(this).start(new BookMarkBean(Long.valueOf(contentId), bookname, String.valueOf(System.currentTimeMillis())));
		//		Bundle bundle = new Bundle();
		//		bundle.putString(DefaultConsts.book_contentId_s, contentId);
		//		bundle.putString(DefaultConsts.book_chapterId_s, chapterId);
		//		updateBookContentIdAction.start(bundle);
	}
	
	private Book createBookForFile(ZLFile file) {
		if (file == null) { return null; }
		Book book = myFBReaderApp.Collection.getBookByFile(file);
		if (book != null) { return book; }
		return null;
	}
	
	public void setScreenBrightness(int percent) {
		if (percent < 1)
		{
			percent = 1;
		}
		else if (percent > 100)
		{
			percent = 100;
		}
		final WindowManager.LayoutParams attrs = getWindow().getAttributes();
		attrs.screenBrightness = percent / 100.0f;
		getWindow().setAttributes(attrs);
		getZLibrary().ScreenBrightnessLevelOption.setValue(percent);
	}
	
	public int getScreenBrightness() {
		final int level = (int) (100 * getWindow().getAttributes().screenBrightness);
		return (level >= 0) ? level : 50;
	}
	
	private BookCollectionShadow getCollection() {
		return (BookCollectionShadow) myFBReaderApp.Collection;
	}
	
	public void setBackGroud(String value) {
		myFBReaderApp.getColorProfile().WallpaperOption.setValue(value);
		AndroidFontUtil.clearFontCache();
		myFBReaderApp.onBookUpdated(myBook);
	}
	
	/**
	 * @Title doBookHighLight
	 * @Description 处理书本高亮处理
	 * @param
	 * @return void
	 * @throws
	 * @Crtdate 2013-11-29下午4:04:59
	 */
	public void doBookHighLight(Object... params) {
		final boolean existingBookmark;
		final Bookmark bookmark;
		
		if (params.length != 0)
		{
			existingBookmark = true;
			bookmark = (Bookmark) params[0];
		}
		else
		{
			existingBookmark = false;
			final FBView fbView = myFBReaderApp.getTextView();
			final String text = fbView.getSelectedText();
			
			bookmark = new Bookmark(myFBReaderApp.Model.Book, fbView.getModel().getId(), fbView.getSelectionStartPosition(), fbView.getSelectionEndPosition(), text, true, contentId, chapterId,2);
			fbView.clearSelection();
		}
		
		myFBReaderApp.getTextView().clearSelection();
		final HighlightingStyle highStyle = new HighlightingStyle(2, "", new ZLColor(16087296));
		myCollection.bindToService(mContext, new Runnable()
		{
			public void run() {
				bookmark.setStyleId(highStyle.Id);
				myCollection.saveBookmark(bookmark);
			}
		});
		
	}
	
	@Override
	public boolean onSearchRequested() {
		Intent intent = new Intent(this, SearchActivity.class);
		startActivity(intent);
		return true;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		boolean isShown = false;
		if (keyCode == event.KEYCODE_BACK)
		{
			
			if (topUtilView.isShown())
			{
				_hideMenu();
				isShown = true;
				return isShown;
			}
			else if (null != popWindowSelection)
			{
				if (popWindowSelection.isShow())
				{
					popWindowSelection.hidePop(true);
					myFBReaderApp.getTextView().clearSelection();
					isShown = true;
				}
				else
				{
					isShown = true;
					this.finish();
				}
			}
			else
			{
				isShown = true;
				this.finish();
			}
		} else if ( keyCode == event.KEYCODE_MENU ) {
			if (topUtilView.isShown())
			{
				_hideMenu();
			} else {
				_showMenu();
			}
			return true;
		}
		return isShown;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ANNOTATION_REQUEST_CODE && resultCode == RESULT_OK) {
			reopenCurrentChapter();
		}
	}
		
	@Override
	public void onConfigurationChanged(Configuration newConfig) { 
	    super.onConfigurationChanged(newConfig); 
		reopenCurrentChapter( );
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	public void finish() {
		myFBReaderApp.storePosition();
		super.finish();
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		myFBReaderApp.getViewWidget().reset();
		myFBReaderApp.getViewWidget().repaint();
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		final String action = intent.getAction();
		if (SHOW_CATALOG.equals(action))
		{
			openBook(intent, null, true, 1);
		}
		else super.onNewIntent(intent);
	}
	
	private void showReadOverDialog() {
		new ReadOverDialog(this).show();
	}
	
	public void HidePopupAndSelectCursor() {
		myFBReaderApp.getTextView().clearSelection();
		SelectCursorPopup.Hide();
	}
	
	class CleanSelectCursor
	        extends
	        BroadcastReceiver
	{
		
		@Override
		public void onReceive(Context context, Intent intent) {
			myFBReaderApp.getTextView().clearSelection();
		}
		
	}
	
	private BroadcastReceiver myBatteryInfoReceiver = new BroadcastReceiver()
	{
        public void onReceive(Context context, Intent intent) {
            final int level = intent.getIntExtra("level", 100);
            BatteryLevel = level;
        }
    };
    
    private void startOpenBook() {
    	getCollection().bindToService(this, new Runnable()
		{
			public void run() {
				openBook(getIntent(), null, false, 3);
			}
		});
    }
    
    void downloadChapterInfo(String chapterId) {
//		new QryChapterInfoAction(this, contentId, chapterId, new ChapterInfoListener()).start();
		new qryChapterInfoUtil().qryChapterInfo(this, contentId, chapterId,new ChapterInfoHandler());
	}
	
	private class ChapterInfoHandler extends TextHttpResponseHandler
	{

		@Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			if (statusCode>1000)
            {
				try
				{
	    			Message msg = Message.obtain();
	    			msg.what = GET_CHAPTERINFO_ERROR;
	    			Bundle bundle = new Bundle();
	    			bundle.putInt("result", statusCode);
	    	        bundle.putString("message", JSONUtil.getString(responseString));
	    			msg.setData(bundle);
	    			myHandler.sendMessage(msg);
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
            }
			
        }

		@Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
			myHandler.sendEmptyMessage(GET_CHAPTERINFO_OK);
        }
		
	}
    
    
	class ChapterInfoListener implements ActionListener {

		@Override
		public void OK(Object obj) {
			myHandler.sendEmptyMessage(GET_CHAPTERINFO_OK);
		}

		@Override
		public void ERROR(int resultCode, String message) {
			Message msg = Message.obtain();
			msg.what = GET_CHAPTERINFO_ERROR;
			Bundle bundle = new Bundle();
			bundle.putInt("result", resultCode);
			bundle.putString("message", message);
			msg.setData(bundle);
			myHandler.sendMessage(msg);
		}

		@Override
		public void HTTPERROR(int statusCode) {

		}

	}
}
